package com.simblog.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.simblog.common.constants.Constants;
import com.simblog.oaknt.domain.Category;
import com.simblog.oaknt.domain.User;
import com.simblog.oaknt.service.ICategoryService;

@Controller
@RequestMapping("v/category")
public class CategoryController extends BaseController{
	private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);
	@Reference
	private ICategoryService categoryService;
	
	@ResponseBody
	@RequestMapping("query")
	public JSONObject list(HttpServletRequest request,String qryName){
		logger.info("获取我的文章分类目录,qryName={}",qryName);
		Map<String, Object> params = new HashMap<String,Object>();
		try{
			User user = getSessionUser(request);
			params.put("userId", user.getId());
			params.put("qryName", qryName);
			List<Category> list = categoryService.queryList(params);
			return assemblyJson(list, Constants.RESP_SUCCESS, "获取成功");
		}catch (Exception e) {
			logger.error("获取我的文章分类目录异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}		
	}
	
	@ResponseBody
	@RequestMapping("unique")
	public JSONObject unique(String name,String value,Long id,HttpServletRequest request){
		logger.info("查询文章分类的唯一性，name={}，value={},id={}",new Object[]{name,value,id});
		Map<String, Object> params = new HashMap<String,Object>();
		try{
			if(StringUtils.isBlank(value)){
				return assemblyJson(null, Constants.RESP_SUCCESS, "成功");
			}
			
			User user = getSessionUser(request);
			params.put("userId", user.getId());
			params.put(name, value);
			List<Category> list = categoryService.queryList(params);
			if(CollectionUtils.isEmpty(list)){
				return assemblyJson(null, Constants.RESP_SUCCESS, "成功");
			}else if(id != null && list.size() == 1 && list.get(0).getId().compareTo(id) == 0){//等价于名字不改
				return assemblyJson(null, Constants.RESP_SUCCESS, "成功");
			}
			return assemblyJson(null, Constants.RESP_FAIL, "分类已存在");
		}catch (Exception e) {
			logger.info("查询文章分类的唯一性异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
	@ResponseBody
	@RequestMapping("insert")
	public JSONObject insert(Category category,HttpServletRequest request){
		logger.info("保存文章分类,name={}",new Object[]{category.getName()});
		try{
			User user = getSessionUser(request);
			category.setIsDefault("0");
			category.setUserId(user.getId());
			categoryService.insert(category);
			return assemblyJson(null, Constants.RESP_SUCCESS, "保存成功");
		}catch (Exception e) {
			logger.info("保存文章分类异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
	@RequestMapping("manage")
	public String manage(HttpServletRequest request,Model model,PageInfo<Category> pageInfo){
		logger.info("分类管理");
		Map<String, Object> params = new HashMap<String,Object>();
		initPage(pageInfo);
		try{
			User user = getSessionUser(request);
			params.put("userId", user.getId());
			pageInfo = categoryService.queryPage(params, pageInfo);
		}catch (Exception e) {
			logger.error("分类管理异常");
			e.printStackTrace();
		}
		model.addAttribute("pageInfo", pageInfo);
		return "category/manage";
	}
	
	@ResponseBody
	@RequestMapping("edit")
	public JSONObject edit(String id){
		logger.info("编辑分类详情，id={}",id);
		
		try{
			Category category = categoryService.selectByPrimaryKey(Long.valueOf(id));
			
			if(category == null){
				return assemblyJson(null, Constants.RESP_FAIL, "获取文章分类信息失败");
			}
			
			return assemblyJson(category, Constants.RESP_SUCCESS, "获取成功");
		}catch (Exception e) {
			logger.error("编辑分类详情异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
	@ResponseBody
	@RequestMapping("update")
	public JSONObject update(Category category,HttpServletRequest request){
		logger.info("更新文章分类，id={},name={},content={},orderIndex={},isDefault={},isPublic={}",new Object[]{category.getId(),category.getName(),category.getContent(),category.getOrderIndex(),category.getIsDefault(),category.getIsPublic()});
		try{
			User user = getSessionUser(request);
			Category temp = categoryService.selectByPrimaryKey(category.getId());
			if(temp == null || temp.getUserId().compareTo(user.getId()) != 0){
				return assemblyJson( null, Constants.RESP_FAIL, "行为异常，无效操作");
			}
			
			category.setCreateTime(null);
			category.setIsDefault(null);
			categoryService.updateByPrimaryKeySelective(category);
			
			return assemblyJson(null, Constants.RESP_SUCCESS, "更新成功");
		}catch (Exception e) {
			logger.error("更新文章分类异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
	@ResponseBody
	@RequestMapping("delete")
	public JSONObject delete(String id,HttpServletRequest request){
		logger.info("删除文章分类，id={}",id);
		
		try{
			User user = getSessionUser(request);
			Category category = categoryService.selectByPrimaryKey(Long.valueOf(id));
			
			if(category == null || category.getUserId().compareTo(user.getId()) != 0){
				return assemblyJson( null, Constants.RESP_FAIL, "行为异常，无效操作");
			}
			
			categoryService.deleteByPrimaryKey(Long.valueOf(id));
			return assemblyJson(null, Constants.RESP_SUCCESS, "删除成功");
		}catch (Exception e) {
			logger.error("删除文章分类异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
	}
	
	
	@ResponseBody
	@RequestMapping("change_default")
	public JSONObject changeDefaultStatus(String isDefault,String id,HttpServletRequest request){
		logger.info("改变文章分类的默认状态，id={},isDefault={}", new Object[]{id,isDefault});
		try{
			User user = getSessionUser(request);
			Category category = categoryService.selectByPrimaryKey(Long.valueOf(id));
			
			if(category == null || category.getUserId().compareTo(user.getId()) != 0){
				return assemblyJson( null, Constants.RESP_FAIL, "行为异常，无效操作");
			}
			
			Category temp = new Category();
			temp.setId(Long.valueOf(id));
			temp.setIsDefault(isDefault);
			if("0".equals(isDefault)){//取消设置为默认
				categoryService.updateByPrimaryKeySelective(temp);
				return assemblyJson(null, Constants.RESP_SUCCESS, "取消默认成功");
			}else if("1".equals(isDefault)){
				Map<String, Object> params = new HashMap<String,Object>();
				params.put("userId", user.getId());
				params.put("isDefault", "1");
				List<Category> list = categoryService.queryList(params);
				if(!CollectionUtils.isEmpty(list)){
					return assemblyJson(null, Constants.RESP_FAIL, "只能设置一个为默认，先取消原来默认的");
				}
				categoryService.updateByPrimaryKeySelective(temp);
				return assemblyJson(null, Constants.RESP_SUCCESS, "设置为默认成功");
			}else{
				return assemblyJson( null, Constants.RESP_FAIL, "行为异常，无效操作");
			}
		}catch (Exception e) {
			logger.info("改变文章分类状态异常");
			e.printStackTrace();
			return assemblyJson(null, Constants.RESP_EXCEPTION, "系统异常");
		}
		
		
		
	}
	
	
	
	
	
	
	
	
}
